<template>
  <div>
    <el-card>
      <el-button type="primary" @click="addRole">添加</el-button>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="180" />
        <el-table-column prop="role_name" label="角色名" />
        <el-table-column label="权限级别" v-slot="{ row }">
          <el-tag type="success" v-if="row.permission_ids === '*'"
            >超级管理员</el-tag
          >
          <el-tag type="primary" v-else>管理员</el-tag>
        </el-table-column>
        <el-table-column prop="address" label="操作" v-slot="{ row }">
          <el-button
            type="success"
            @click="allocationPermission(row)"
            :disabled="row.permission_ids === '*'"
            >权限</el-button
          >
          <el-button type="primary" @click="editRole(row)">编辑</el-button>
          <el-button type="danger" @click="delRole(row)">删除</el-button>
        </el-table-column>
      </el-table>
      <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="total"
        class="mt-4"
        :page-size="pageSize"
        @change="changePage"
        style="display: flex; justify-content: center"
      />
    </el-card>
    <el-drawer
      v-model="drawer"
      :title="'分配' + roleInfo.role_name + '权限'"
      :with-header="true"
      ><el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="permissionTree"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkedPermission"
        :props="defaultProps"
      />
      <el-button
        type="primary"
        style="margin: 30px 0"
        @click="confirmPermission"
        >确定</el-button
      >
    </el-drawer>
    <!-- 添加对话框 -->
    <el-dialog v-model="dialogVisible" title="添加" width="500">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名">
          <el-input
            v-model="ruleForm.role_name"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            ref="addTreeRef"
            style="max-width: 600px"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="ConfirmAdd"> Confirm </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="editdialogVisible" title="编辑" width="500">
      <el-form
        ref="editruleFormRef"
        style="max-width: 600px"
        :model="editruleForm"
        status-icon
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名">
          <el-input
            v-model="editruleForm.role_name"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editdialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="ConfirmEdit"> Confirm </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  reqRolesList,
  reqPermissionsList,
  reqUpdateRolePermission,
  reqDelRole,
  reqAddRole,
} from "@/api/roles/index";
import { ResRolesList, ResPermissionsList } from "@/api/roles/model";
import { buildTree } from "@/utils/buildTree";
import { ref, onMounted } from "vue";
const page = ref<number>(1);
const pageSize = ref<number>(6);
const total = ref<number>(0);
const tableData = ref<ResRolesList[]>([]);
const drawer = ref<boolean>(false);
const roleInfo = ref<Partial<ResRolesList>>({});
const permissionTree = ref<ResPermissionsList[]>([]);
const treeRef = ref<InstanceType<typeof ElTree>>();
const addTreeRef = ref<InstanceType<typeof ElTree>>();
const checkedPermission = ref([]);
const dialogVisible = ref(false);
const editdialogVisible = ref(false);
const ruleForm = ref({
  role_name: "",
  permission_ids: "",
});
const editruleForm = ref({
  role_name: "",
  permission_ids: "",
});
const input = ref<string>("");

const defaultProps = {
  children: "children",
  label: "permission_name",
};

// 删除角色
const delRole = (row: any) => {
  ElMessageBox.confirm(`确定删除${row.role_name}角色吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  })
    .then(async () => {
      await reqDelRole(row.id);
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getrolesList();
    })
    .catch(() => {});
};
// 添加角色
const addRole = async () => {
  let result = await reqPermissionsList();
  permissionTree.value = buildTree(result);
  dialogVisible.value = true;
};
// 编辑角色
const editRole = (row: any) => {
  roleInfo.value = row;
  editruleForm.value.role_name = row.role_name;
  editdialogVisible.value = true;
};

// 确认添加
const ConfirmAdd = async () => {
  let addTreeRefStr = addTreeRef.value!.getCheckedKeys().join(",");
  ruleForm.value.permission_ids = addTreeRefStr;
  console.log(ruleForm.value);
  await reqAddRole(ruleForm.value);
  ElMessage({
    message: "添加成功",
    type: "success",
  });
  getrolesList();
  dialogVisible.value = false;
};
// 确认编辑
const ConfirmEdit = async () => {
  if (roleInfo.value.id && roleInfo.value.permission_ids) {
    await reqUpdateRolePermission({
      id: roleInfo.value.id,
      permission_ids: roleInfo.value.permission_ids,
      role_name: editruleForm.value.role_name,
    });
    getrolesList();
    editdialogVisible.value = false;
  }
};

// 确认修改权限
const confirmPermission = async () => {
  if (roleInfo.value.id) {
    let checkedKeysStr = treeRef.value!.getCheckedKeys().join(",");
    await reqUpdateRolePermission({
      id: roleInfo.value.id,
      permission_ids: checkedKeysStr,
    });
    drawer.value = false;
    getrolesList();
  }
};

const changePage = (pageNum: number) => {
  page.value = pageNum;
  getrolesList();
};

// 获取权限列表
const allocationPermission = async (row: any) => {
  let result = await reqPermissionsList();
  permissionTree.value = buildTree(result);
  roleInfo.value = row;
  drawer.value = true;
  checkedPermission.value = row.permission_ids
    .split(",")
    .map((item: any) => parseInt(item));
};

// 获取角色列表
const getrolesList = async () => {
  let data = await reqRolesList({
    page: page.value,
    pageSize: pageSize.value,
    keyword: input.value,
  });
  tableData.value = data.rows;
  total.value = data.count;
};

onMounted(() => {
  getrolesList();
});
</script>

<style scoped lang="scss"></style>
